<?php
/**
 * ============================================================================
 * @package Forum
 * @author Andy
 * @version 15:54
 * @link https://sjdphp.com
 * @desc 订阅管理员登陆
 * ----------------------------------------------------------------------------
 */

namespace app\admin\subscribe;


use app\common\model\BackLog as BackLogModel;
use app\common\server\Json;
use app\common\server\SystemLog;
use think\Event;
use think\facade\Cookie;

class BackLog
{
    /** 订阅管理员登陆操作
     * @param $backInfo
     * @return \think\response\Json
     */
    public function onBackSignIn($backInfo){
        ## 记录登陆日记
        $token = md5("back_id:" . $backInfo["back_id"].'&time='. time());

        ## 查询原来是否有登陆的信息
        try{
            $logInfo = BackLogModel::where(array('back_id' => $backInfo["back_id"],'log_status' => 0))->find();
        }catch(\Exception $e){
            SystemLog::insertLog($e->getMessage());
            return Json::error('系统错误,请稍后重试');
        }

        ## 判断是否存在登陆日志
        if(!empty($logInfo)){
            $logInfo->log_status = 1;
            $logInfo->save();
        }

        $endTime = time() + config("project.back_cookie.default_time");

        ## 新增登陆日志
        $log = array(
            'back_id'   => $backInfo["back_id"],
            'back_name' => $backInfo['username'],
            'login_ip'  => getIp(),
            'login_status' => 0,
            'login_token'  => $token,
            'end_time'     => $endTime
        );

        try{
            BackLogModel::create($log);
        }catch(\Exception $e){
            SystemLog::insertLog($e->getMessage());
        }

        Cookie::set(config("project.back_cookie.cookie_name"),$token);
    }

    /** 订阅管理员退出登陆操作
     * @return \think\response\Json
     */
    public function onBackSignOut(){
        ## 获取token
        $token = Cookie::get(config("project.back_cookie.cookie_name"));

        ## 查询token是否有效
        try{
            $backLog = BackLogModel::where(array('login_token' => $token,'log_status' => 0))->find();
        }catch(\Exception $e){
            SystemLog::insertLog($e->getMessage());
            return Json::error('系统错误,请稍后重试');
        }

        if(empty($backLog)){
            return Json::error("登陆已过期");
        }

        ## 修改登陆日志
        try{
            $backLog->log_status = 1;
            $backLog->save();
        }catch(\Exception $e){
            SystemLog::insertLog($e->getMessage());
        }

        ## 清除Cookie
        Cookie::delete(config("project.back_cookie.cookie_name"));
    }

    public function subscribe(Event $event){
        $event->listen("BackSignIn",[$this,'onBackSignIn']);
        $event->listen("BackSignOut",[$this,"onBackSignOut"]);
    }
}